/**
 * 
 */
package com.warrant.module.rpa.finance;

import com.eos.foundation.common.utils.StringUtil;
import com.eos.system.annotation.Bizlet;
import com.eos.system.annotation.BizletParam;
import com.eos.system.annotation.ParamType;
import com.eos.system.exception.EOSRuntimeException;
import com.primeton.ext.data.sdo.DataUtil;
import com.primeton.ext.data.sdo.ExtendedDataObject;
import com.primeton.ext.data.sdo.ExtendedType;
import com.primeton.ext.data.sdo.helper.ExtendedTypeHelper;

import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Type;
import commonj.sdo.helper.DataFactory;

/**
 * @author cn
 * @date 2020-08-21 10:43:33
 * 
 */
@Bizlet("")
public class DataObjectUtil {

	@Bizlet(value = "Use the dataObject's full name to ctreate it", params = { @BizletParam(index = 0, type = ParamType.CONSTANT) })
	public static DataObject createDataObject(String entityName) {
		if (StringUtil.isBlank(entityName))
			return null;
		ExtendedType type = (ExtendedType) ExtendedTypeHelper.eINSTANCE.getType(entityName);
		if (type == null)
			throw new EOSRuntimeException("24000021", new String[] { entityName });
		return DataFactory.INSTANCE.create((Type) type);
	}

	/**
	 * 重置dataObject数据
	 * 
	 */
	public static void resetDataObject(DataObject srcDataObject) {
		for (Object p : ((ExtendedDataObject) srcDataObject).getInstanceProperties()) {
			Property srcProp = (Property) p;
			String propertyName = srcProp.getName();
			srcDataObject.set(propertyName, srcProp.getDefault());
		}
	}

	@Bizlet(value = "Convert the dataobject to specified dataOjbect", params = { @BizletParam(index = 1, type = ParamType.CONSTANT), @BizletParam(index = 2, type = ParamType.CONSTANT) })
	public static DataObject convertDataObject(DataObject srcDataObject, String entityName, boolean convertAll) {
		if (srcDataObject == null)
			return null;
		if (StringUtil.isBlank(entityName))
			throw new EOSRuntimeException("24000001", new String[] { "entityName" });
		DataObject targetDataObject = createDataObject(entityName);
		resetDataObject(targetDataObject);
		for (Object p : ((ExtendedDataObject) srcDataObject).getInstanceProperties()) {
			Property srcProp = (Property) p;
			if (srcDataObject.isSet(srcProp)) {
				Object value = srcDataObject.get(srcProp);
				String propertyName = srcProp.getName();
				Property targetProp = targetDataObject.getInstanceProperty(propertyName);
				if (null != targetProp) {
					if (targetProp.getType().isDataType()) {
						targetDataObject.set(propertyName, DataUtil.toSDOValue(targetProp.getType(), value));
						continue;
					}
					targetDataObject.set(propertyName, value);
					continue;
				}
				if (convertAll && targetDataObject.getType().isOpen())
					targetDataObject.set(propertyName, value);
			}
		}
		return targetDataObject;
	}

}
